/*
** Copyright (C) 2011 Viens Yann
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#include <QString>
#include <cstdlib>
#include "ScoreLoader.hpp"

ScoreLoader::ScoreLoader(): _nextToCall(NULL)
{
  _filler["nickname"] = &ScoreLoader::loadNickName;
  _filler["score"] = &ScoreLoader::loadScore;
}

bool	ScoreLoader::startElement(const QString&, const QString& localName, const QString&, const QXmlAttributes&)
{
  std::map<std::string, loaderMember>	::iterator		itBegin = _filler.begin();
  const std::map<std::string, loaderMember>::iterator	itEnd = _filler.end();

  while (itBegin != itEnd && (*itBegin).first != localName.toStdString())
    ++itBegin;
  if (itBegin != itEnd)
    {
      _nextToCall = (*itBegin).second;
    }
  return true;
}

bool	ScoreLoader::endElement(const QString&, const QString& localName, const QString&)
{
  _nextToCall = 0;
  if (localName.toStdString() == "position")
    {
      _score.push_back(_currentItem);
    }
  return true;
}

bool	ScoreLoader::characters(const QString &str)
{
  if (_nextToCall)
    (this->*_nextToCall)(str);
  return true;
}

bool	ScoreLoader::fatalError(const QXmlParseException &)
{
  return true;
}

void	ScoreLoader::loadNickName(QString const& nickName)
{
  _currentItem.first = nickName.toStdString();
}

void	ScoreLoader::loadScore(QString const& score)
{
  _currentItem.second = atoi(score.toStdString().data());
}

std::list<std::pair<std::string, int> >	ScoreLoader::getScores()
{
  return _score;
}
